package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/v1/file/")
public class UplateController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile  file) throws IOException {
        //1.获取原文件名
        String filename=file.getOriginalFilename();
        //2.获取文件后缀
        String suffix=filename.substring(filename.lastIndexOf("."));
        //3.生成新的文件名
        filename= UUID.randomUUID()+suffix;
        //4.处理日期路径
        String dirPath="D:/files";
        SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath= sdf.format(new Date());
        //5.创建目录
        File file1=new File(dirPath+datePath);
        if(!file1.exists()){
            file1.mkdirs();
        }
        //6.保存文件
        String filePath=dirPath+datePath+filename;
        file.transferTo(new File(filePath));
        log.debug("上传文件:{}",filePath);
        return JsonResult.ok(datePath+filename);
    }
}
